<?php
include_once("db_connection.php");

$AUTH_NO_SESSION = 0;
$AUTH_INVALID_USER = 1;
$AUTH_INVALID_KEY = 2;
$AUTH_EXPIRE = 3;

function getUserByEmail($email)
{
    $conn = getdb();
    $stmt = $conn->prepare("SELECT * FROM  users WHERE email=:email");
    $stmt->bindParam(':email', $email);
    $stmt->execute();

    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $user = $stmt->fetch();
    return $user;
}

function validateSession()
{
    global $AUTH_NO_SESSION, $AUTH_INVALID_USER, $AUTH_INVALID_KEY, $AUTH_EXPIRE;

    if (!empty($_SESSION['ierg4210']) && !empty($_COOKIE['auth'])) {
        //validate the token
        $token = $_SESSION['ierg4210'];
        $expire = $token['expire'];
        if ($expire < time()) {
            //expire
            return array("result" => false, "error" => $AUTH_EXPIRE);
        } else {
            if ($token['key'] != $_COOKIE['auth']) {
                return array("result" => false, "error" => $AUTH_INVALID_KEY);
            } else {
                // session is not expired and is valid (because PHPSESSID)
                //all validation pass
                updateSessionAndCookie();
                return array("result" => true);
            }
        }

    } else {
        return array("result" => false, "error" => $AUTH_NO_SESSION);
    }
}

function createSession($email, $role, $username, $uid)
{
    $token = array('email' => $email, "username" => $username, "role" => $role, "uid" => $uid);
    $_SESSION['ierg4210'] = $token;
}



function updateSessionAndCookie()
{
    $expire = time() + 60 * 60 * 3;//test expiration 60
    $token = md5("random" . $expire . rand(0, 9999));
    setcookie("auth", $token, $expire, '', '', true, true);//test expiration +120
    $_SESSION['ierg4210']['expire'] = $expire;
    $_SESSION['ierg4210']['key'] = $token;
}

function getCurrentUsername()
{
    $authResult = validateSession();

    if ($authResult['result'] == true) {
        $authResult['username'] = $_SESSION['ierg4210']['username'];
    }
    return $authResult;
}

//$token = array('email' => $user['email'], "expire" => $expire, "key" => hash_hmac("sha256", $expire . $user['pass_hash'], $user['salt']));
//    setcookie("auth", json_encode($token), $expire, '', '', false, true);

//$token = json_decode($_COOKIE['auth'],true);
//
//if ($user==null){
//    //invalid user
////                validationFail("Invalid session 0");
//    return array("result"=>false,"error"=>$AUTH_INVALID_USER);
//}else{
//    $session_hash = hash_hmac("sha256", $expire . $user['pass_hash'], $user['salt']);
//    if ($session_hash!=$token['key']){
//        //invalid key
//        return array("result"=>false,"error"=>$AUTH_INVALID_KEY);
//    }else{
//
//    }
//}